package com.xuan.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.xuan.mapper.AccountMapper;
import com.xuan.model.entity.User;
import com.xuan.model.respons.ResultBody;
import com.xuan.service.AccountService;
import com.xuan.utils.JudgeOb;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
@Slf4j
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountMapper accountMapper;

    @Override
    public Map login(User user) {

        Map<String,Object> map = new HashMap<>();
        map.put("ResultBody",new ResultBody().Fail());
        if (JudgeOb.isNotEmptyBean(user)){
            User userdb = accountMapper.selectById(user.getUsername());

            if (Objects.nonNull(userdb)){

                boolean flag = new BCryptPasswordEncoder().matches(user.getPwd(),userdb.getPwd());


                if (flag){

                    JSONObject userInfo = new JSONObject();

                    userInfo.put("username", userdb.getUsername());

                    List<String> roles = new ArrayList<>();

                    roles.add(userdb.getRoles());

                    userInfo.put("roles", roles);

                    //response.addHeader("AccountInfo", userInfo.toJSONString());

                    map.put("AccountInfo",userInfo.toJSONString());

                    JSONObject result = new JSONObject();

                    result.put("code", 0);

                    log.info("响应头数据为====AccountInfo:"+userInfo);

                    map.put("ResultBody",new ResultBody().OK());
                }

                return map;
            }
        }
        return map;
    }

    @Override
    public User findOne(String username) {
        User user = accountMapper.selectById(username);
        return user;
    }

    @Override
    public ResultBody updateRoles(User user) {
        int i = accountMapper.updateById(user);

        return i > 0 ? new ResultBody().OK() : new ResultBody().Fail();
    }
}
